package de.fhk.fst.dvr.user;

import de.fhk.fst.dvr.BaseController

class UserController extends BaseController {

  def scaffold = true

  def login = {
  }

  def logout = {
    if (session.user) {
      session.user = null
      session.admin = null
      session.invalidate()
      redirect(controller:"index", action:"index")
    }
  }

  def authenticate = {
    def user = User.findByUsernameAndPassword(params.username, params.password.encodeAsSHA())
    if (user) {
      session.user = user
      if (user.isAdmin()) {
        session.admin = true
        redirect(controller: "recordingRequestAdmin", action:"showPending")
      } else {
        redirect(controller: "recordingRequest", action:"create")
      }
    } else {
      redirect(action:"login")
    }
  }

  def register = {
    def userInstance = new User()
    userInstance.properties = params
    return [userInstance: userInstance]
  }

  def update = {
    def formPassword = params.password
    def formPasswordRepeat = params.password_repeat
    def userInstance = User.get(params.id)

    if ((formPassword && formPassword.trim().isEmpty() && formPasswordRepeat && formPasswordRepeat.trim().isEmpty()) || (formPassword == formPasswordRepeat)) {
      if (userInstance) {
        if (params.version) {
          def version = params.version.toLong()
          if (userInstance.version > version) {
            userInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [
              message(code: 'user.label', default: 'User')]
            as Object[], "Another user has updated this User while you were editing")
            render(view: "edit", model: [userInstance: userInstance])
            return
          }
        }
        def password = userInstance.password
        userInstance.properties = params
        if (!params.password || params.password.trim().isEmpty()) {
          userInstance.password = password
        }
        if (!userInstance.hasErrors() && userInstance.save(flush: true)) {
          flash.message = "${message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.username])}"
          redirect(action: "show", id: userInstance.id)
        } else {
          render(view: "edit", model: [userInstance: userInstance])
        }
      }
    } else {
      flash.message = "passwords do not match"
      render(view: "edit", model: [userInstance: userInstance])
    }
  }

  def store = {
    if (params.password == params.password_repeat) {
      def user = new User(params)
      if (user.save(flush:true)) {
        flash.message = "User successfully registerd"
        redirect(controller:"user", action:"login")
      } else {
        flash.message = "User exists"
        redirect(action: "register", model: [userInstance: user])
      }
    } else {
      flash.message = "Passwords do not match"
      redirect(action: "register", model: [userInstance: new User(params)])
    }
  }
}
